package net.homeip.dometec.autodownloadfatto;

import static net.homeip.dometec.autodownloadfatto.MainWindow.nf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JProgressBar;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

public class HttpAccess {

	public static final Pattern searchVars = Pattern.compile("id=\"([^\"]*)\" value=\"([^\"]*)\"");
	public static final String HOST = "http://www.ilfattoquotidiano.it";
	public static final String AUTH_URL = "/login/";
	public static final String GETPDF_URL = "/openpdf/";

	public static final String viewStateName = "__VIEWSTATE";
	public static final String eventValidationName = "__EVENTVALIDATION";

	public String viewState;
	public String eventValidation;

	private HttpClient httpClient;

	public HttpAccess() throws HttpException, IOException {
		httpClient = new HttpClient();
		httpClient.getParams().setParameter("http.protocol.single-cookie-header", true);
		// getSessionVars();
	}

	// private void getSessionVars() throws HttpException, IOException {
	//
	// GetMethod getAuth = new GetMethod(HOST + AUTH_URL);
	// httpClient.executeMethod(getAuth);
	// String page = getAuth.getResponseBodyAsString();
	//
	// Matcher matcher = searchVars.matcher(page);
	// while (matcher.find()) {
	// if (matcher.groupCount() == 2) {
	// if (viewStateName.equals(matcher.group(1))) {
	// viewState = URLEncoder.encode(matcher.group(2), "UTF-8");
	// } else if (eventValidationName.equals(matcher.group(1))) {
	// eventValidation = URLEncoder.encode(matcher.group(2), "UTF-8");
	// }
	// }
	// }
	//
	// }

	public boolean autentica(String username, String password) throws Exception {

		username = URLEncoder.encode(username, "UTF-8");
		password = URLEncoder.encode(password, "UTF-8");

		PostMethod postAuth = new PostMethod(HOST + AUTH_URL);
		postAuth.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		
		RequestEntity rq = new StringRequestEntity("log=" + username + "&pwd=" + password
				+ "&_wp_original_http_referer=http%3A%2F%2Fwww.ilfattoquotidiano.it%2Fabbonati%2F&wp-submit=Log+In&"
				+ "redirect_to=http%3A%2F%2Fwww.ilfattoquotidiano.it%2Fwp-admin%2F&testcookie=1",
				"application/x-www-form-urlencoded", "UTF-8");

		postAuth.setRequestEntity(rq);
		postAuth.setQueryString("action=login&instance=tml-page");

		int httpStatus = httpClient.executeMethod(postAuth);

		if (httpStatus == 302)
			return true;
		return false;

	}

	public String recuperaPdf(String outdir, int anno, int mese, int giorno, JFrame mainWindow, JProgressBar progressBar)
			throws HttpException, IOException {

		GetMethod getPdf = new GetMethod(HOST + GETPDF_URL);
		getPdf.setQueryString("n=" + String.valueOf(anno) + nf.format(mese) + nf.format(giorno));
		getPdf.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		
		int httpStatus = httpClient.executeMethod(getPdf);

		String filename = "ilfatto" + anno + nf.format(mese) + nf.format(giorno) + ".html";

		if (httpStatus == 200 && getPdf.getResponseContentLength() > 30)
			filename = filename.replace(".html", ".pdf");

		filename = outdir + File.separator + filename;

		InputStream asStream = getPdf.getResponseBodyAsStream();
		progressBar.setMaximum((int) getPdf.getResponseContentLength());
		progressBar.setValue(0);

		FileOutputStream file = new FileOutputStream(filename + ".tmp");

		byte buf[] = new byte[1024];
		int len;
		while ((len = asStream.read(buf)) > 0) {
			file.write(buf, 0, len);
			progressBar.setValue(progressBar.getValue() + len);
			mainWindow.repaint();
		}
		file.close();
		asStream.close();

		new File(filename + ".tmp").renameTo(new File(filename));

		progressBar.setValue(progressBar.getMaximum());

		return filename;

	}
}
